const querystring = require('querystring');
const JWT = require('./util/JWT');

const handleUserRoute = require('./src/routes/admin/user');
const handleManagerRoute = require('./src/routes/admin/manager');
const handleProductRoute = require('./src/routes/admin/product');
const handleBannerRoute = require('./src/routes/admin/banner');
const handleOrderRoute = require('./src/routes/admin/order');

const getPostData = req => {
    // console.log('这是req',req);
    //处理post请求
    const promise = new Promise((resolve, reject) => {
        if (req.method !== 'POST') { //如果不是POST请求
            resolve();
            return;
        }

        if (req.headers['content-type'] !== 'application/json') {//如果不是json字符串类型
            resolve({
                name: req.headers['content-type'],
                msg: '不是json字符串类型'
            });
            return;
        }

        let postData = '';

        req.on('data', chunk => {
            postData += chunk.toString();
        });

        req.on('data', () => {
            if (!postData) {
                resolve({});
                return;
            }
            resolve(JSON.parse(postData));
        });
    });

    return promise;
}

const serverHeadler = (req, res) => {
    //设置相应格式
    res.setHeader('content-Type', 'application/json;charset=utf-8')
    res.setHeader("Access-Control-Allow-Headers", "*");
    res.setHeader("Access-Control-Allow-Methods", "*");
    res.setHeader("Access-Control-Allow-Origin", '*');

    console.log('请求方式', req.method);
    if (req.method === 'OPTIONS') {
        res.end()
    } else {

        //获取path
        const url = req.url;
        req.path = url.split('?')[0];

        //解析query
        req.query = querystring.parse(url.split('?')[1]);

        // 设置token
        // if (url !== '/api/manager/login') {
        //     console.log('生成token');
        //     const token = req.headers['token'].split(' ')[1];
        //     console.log('我是携带上的token',token);
        //     if (token) {
        //         var payload = JWT.verify(token);
        //         if (payload) {
        //             const newToken = JWT.generate({ managerAccount: payload.managerAccount }, '1d');
        //             res.setHeader('token', newToken);
        //         } else {
        //             res.writeHead(401);
        //             res.write('token过期了');
        //             res.end();
        //         } 
        //     }
        // }



        getPostData(req).then(postData => {
            req.body = postData;
            console.log('前端给后端的数据', postData);
            const nowPath = req.path.split('/')[2];

            if (nowPath === 'user') {
                //用户相关路由 
                const userDataPromise = handleUserRoute(req, res);
                if (userDataPromise) {
                    userDataPromise.then(userData => {
                        console.log('给前端返回的用户数据', userData);
                        if (url === '/api/user/login' && userData.data) {
                            const token = JWT.generate({ userId: postData.userId, userAccount: postData.userAccount, userAvatar: postData.userAvatar }, "1d");
                            console.log('设置token', token);
                            userData.data.token = token;
                        }
                        res.end(JSON.stringify(userData));
                    });
                    return;
                }
            }

            if (nowPath === 'manager') {
                //管理员相关路由
                const managerDataPromise = handleManagerRoute(req, res);
                if (managerDataPromise) {
                    managerDataPromise.then(managerData => {
                        console.log('后端给前端返回的数据', managerData);

                        //管理员登录
                        if (url === '/api/manager/login' && managerData.data) {
                            const token = JWT.generate({ managerId: postData.managerId, managerAccount: postData.managerAccount, managerAvatar: postData.managerAvatar }, "1d");
                            console.log('设置token', token);
                            managerData.data.token = token;
                        }

                        res.end(JSON.stringify(managerData));
                    });
                    return;
                }
            }

            if (nowPath === 'product') {
                //产品相关路由
                const productDataPromise = handleProductRoute(req, res);
                if (productDataPromise) {
                    productDataPromise.then(productData => {
                        console.log('给前端返回的数据', productData);
                        res.end(JSON.stringify(productData));
                    });
                    return;
                }
            }


            if (nowPath === 'banner') {
                //轮播图相关路由
                const bannerDataPromise = handleBannerRoute(req, res);
                if (bannerDataPromise) {
                    bannerDataPromise.then(bannerData => {
                        console.log('给前端返回的数据', bannerData);
                        res.end(JSON.stringify(bannerData));
                    });
                    return;
                }
            }

            if (nowPath === 'order') {
                //订单相关路由
                const orderDataPromise = handleOrderRoute(req, res);
                if (orderDataPromise) {
                    orderDataPromise.then(orderData => {
                        console.log('给前端返回的数据', orderData);
                        res.end(JSON.stringify(orderData));
                    });
                    return;
                }
            }

            //未匹配到任何路由
            res.writeHead(404, { 'Content-Type': 'text/plain' });
            res.write('404 Not Found');
            res.end();
        })
    }
}

module.exports = serverHeadler;